<?php
session_start();

if ( !$_SESSION['manager'] )
{
    header('Location: index.php');
    exit();
}
else
{
    require_once('inc/config.db.php');

    if ( isset($_POST['email_password']) && ($_POST['email_password']=='') ) { $_POST['email_password']='NULL'; }

    switch($_POST['action'])
    {
/*
#	СОЗДАНИЕ клиента
*/
	case	'customer.new.do':
	    mysql_query('START TRANSACTION');
	    mysql_query('INSERT INTO `account` SET `saas_id`=1');
	    $account_id = mysql_insert_id();

// Если есть номера договоров, упаковывем в массив
	    for ( $i=0; $i<sizeof($_POST['contract_num']); $i++ )
	    {
		if ( !empty($_POST['contract_num'][$i]) )
		{
		    $contract_new[] = array
		    (
			'contract_number'	=> $_POST['contract_num'][$i],
			'accepted_date'		=> $_POST['date_contract'][$i],
			'end_date'			=> $_POST['end_date'][$i],
			'executive_id'		=> $_POST['executive_contract'][$i],
		    );
		}
	    }

// Если клиенту установлены доп.поля, упаковывем их в массив
	    for ( $i=0; $i<sizeof($_POST['arbitrary_field']); $i++ )
	    {
		if ( !empty($_POST['arbitrary_field'][$i]) )
		{
		    $arbitrary_new[] = array
		    (
			'id'	=> $_POST['arb_field_name_id'][$i],
			'value'	=> $_POST['arbitrary_field'][$i],
		    );
		}
	    }

// Если есть массив с договорами, начинаем их (договора) создавать в БД
	    if ( is_array($contract_new) )
	    {
		foreach ( $contract_new as $value )
		{
		    $query = sprintf('INSERT INTO `contract` (`contract_number`,`executive_id`,`account_id`) VALUES (\'%s\',%d,%d)',$value['contract_number'],$value['executive_id'],$account_id);
		    mysql_query($query);

		    if ( $contract_id = mysql_insert_id() )
		    {
				if ( !empty($value['accepted_date']) )
				{
				    $query = sprintf('UPDATE `contract` SET `accepted_date`=\'%s\' WHERE `id`=%d',$value['accepted_date'],$contract_id);
				    mysql_query($query);
				}
				else
				{
					$query = sprintf('UPDATE `contract` SET `accepted_date`=Now() WHERE `id`=%d',$contract_id);
				    mysql_query($query);	
				}

				if ( !empty($value['end_date']) )
				{
				    $query = sprintf('UPDATE `contract` SET `end_date`=\'%s\' WHERE `id`=%d',$value['end_date'],$contract_id);
				    mysql_query($query);
				}
		    }
		}

		if ( $err = mysql_error() ) { die($query.'<br/>'.$err); }
	    }

// Создаём непосредственно клиента в БД
	    mysql_query
	    (
		sprintf
		(
		    'INSERT INTO `customer` SET '
			.'`account_id`=%d,'
			.'`manager_id`=%d,'
			.'`customer_name`=\'%s\','
			.'`email`=\'%s\','
			.'`password`=\'%s\','
			.'`group_id`=%d,'
			.'`status_id`=%d,'
			.'`legal_region`=\'%s\','
			.'`legal_city`=\'%s\','
			.'`legal_index`=%d,'
			.'`legal_street`=\'%s\','
			.'`legal_home`=%d,'
			.'`legal_litera`=\'%s\','
			.'`legal_office`=\'%s\','
			.'`actual_region`=\'%s\','
			.'`actual_city`=\'%s\','
			.'`actual_index`=%d,'
			.'`actual_street`=\'%s\','
			.'`actual_home`=%d,'
			.'`actual_litera`=\'%s\','
			.'`actual_office`=\'%s\','
			.'`postal_region`=\'%s\','
			.'`postal_city`=\'%s\','
			.'`postal_index`=%d,'
			.'`postal_street`=\'%s\','
			.'`postal_home`=%d,'
			.'`postal_litera`=\'%s\','
			.'`postal_office`=\'%s\','
			.'`inn`=\'%s\','
			.'`okonh`=\'%s\','
			.'`okpo`=\'%s\','
			.'`kpp`=\'%s\','
			.'`bank`=\'%s\','
			.'`current_account`=\'%s\','
			.'`korr_account`=\'%s\','
			.'`bik`=\'%s\','
			.'`create_date`=NOW(),'
			.'`is_deleted`=NULL',
		    $account_id,
		    mysql_escape_string($_POST['manager']),
		    mysql_escape_string($_POST['name']),
		    mysql_escape_string($_POST['email']),
		    mysql_escape_string($_POST['email_password']),
		    mysql_escape_string($_POST['group']),
		    mysql_escape_string($_POST['status']),
		    mysql_escape_string($_POST['legal_region']),
		    mysql_escape_string($_POST['legal_city']),
		    mysql_escape_string($_POST['legal_index']),
		    mysql_escape_string($_POST['legal_street']),
		    mysql_escape_string($_POST['legal_home']),
		    mysql_escape_string($_POST['legal_litera']),
		    mysql_escape_string($_POST['legal_office']),
		    mysql_escape_string($_POST['actual_region']),
		    mysql_escape_string($_POST['actual_city']),
		    mysql_escape_string($_POST['actual_index']),
		    mysql_escape_string($_POST['actual_street']),
		    mysql_escape_string($_POST['actual_home']),
		    mysql_escape_string($_POST['actual_litera']),
		    mysql_escape_string($_POST['actual_office']),
		    mysql_escape_string($_POST['postal_region']),
		    mysql_escape_string($_POST['postal_city']),
		    mysql_escape_string($_POST['postal_index']),
		    mysql_escape_string($_POST['postal_street']),
		    mysql_escape_string($_POST['postal_home']),
		    mysql_escape_string($_POST['postal_litera']),
		    mysql_escape_string($_POST['postal_office']),
		    mysql_escape_string($_POST['inn']),
		    mysql_escape_string($_POST['okonh']),
		    mysql_escape_string($_POST['okpo']),
		    mysql_escape_string($_POST['kpp']),
		    mysql_escape_string($_POST['bank_name']),
		    mysql_escape_string($_POST['account_r']),
		    mysql_escape_string($_POST['account_k']),
		    mysql_escape_string($_POST['bic'])
		)
	    );

// Если клиент успешно записан в БД, завершаем транзакцию, и делаем редирект на карточку нового клиента
	    if ( mysql_affected_rows()==1 )
	    {
		$id = mysql_insert_id();

		if ( is_array($arbitrary_new) )
		{
		    foreach ( $arbitrary_new as $field )
		    {
			$query = sprintf('INSERT INTO `arbitrary_field` (`customer_id`,`field_name_id`,`value`) VALUES (%d,%d,\'%s\')',$id,$field['id'],mysql_escape_string($field['value']));
			mysql_query($query);
		    }
		}

		mysql_query('COMMIT');
		header('Location: customer-edit.php?id='.$id);
	    }
// Иначе выводим ошибку
	    else
	    {
		print "Some error:";
		print mysql_error();
	    }
	    break;

/*
#	РЕДАКТИРОВАНИЕ клиента
*/
	case	'customer.edit.do':
	    if ( isset($_POST['id']) )
	    {
		$result = mysql_query('SELECT `id`,`account_id` FROM `customer` WHERE `id`='.$_POST['id']);
		if ( mysql_affected_rows()==1 )
		{
		    $customer = mysql_fetch_assoc($result);

		    foreach ( $_POST as $key => $value )
		    {
			if ( $contract_id = preg_replace('/^contract_num_(\d+)$/', '$1', $key) )
			{
			    if ( is_numeric($contract_id) )
			    {
				$contract_upd[$contract_id] = array
				(
				    'contract_number'	=> $_POST['contract_num_'.$contract_id],
				    'accepted_date'	=> $_POST['date_contract_'.$contract_id],
				    'end_date'	=> $_POST['date_contract_end_'.$contract_id],
				    'prepayment'	=> $_POST['prepayment_'.$contract_id],
				    'executive_id'	=> $_POST['executive_contract_'.$contract_id],
				);
			    }
			}

			if ( $field_id = preg_replace('/^arbitrary_field_(\d+)$/', '$1', $key) )
			{
			    if ( is_numeric($field_id) )
			    {
				$arbitrary_upd[$field_id] = $value;
			    }
			}
		    }

		    for ( $i=0; $i<sizeof($_POST['contract_num']); $i++ )
		    {
			if ( !empty($_POST['contract_num'][$i]) )
			{
			    $contract_new[] = array
			    (
				'contract_number'	=> $_POST['contract_num'][$i],
				'accepted_date'		=> $_POST['date_contract'][$i],
				'end_date'			=> $_POST['end_date'][$i],
				'executive_id'		=> $_POST['executive_contract'][$i],
			    );
			}
		    }

		    for ( $i=0; $i<sizeof($_POST['arbitrary_field']); $i++ )
		    {
			if ( !empty($_POST['arbitrary_field'][$i]) )
			{
			    $arbitrary_new[] = array
			    (
				'id'	=> $_POST['arb_field_name_id'][$i],
				'value'	=> $_POST['arbitrary_field'][$i],
			    );
			}
		    }

		    mysql_query('START TRANSACTION');

		    if ( is_array($contract_new) )
		    {
			foreach ( $contract_new as $value )
			{
			    $query = sprintf('INSERT INTO `contract` (`contract_number`,`executive_id`,`account_id`) VALUES (\'%s\',%d,%d)',$value['contract_number'],$value['executive_id'],$customer['account_id']);
			    mysql_query($query);

			    if ( $contract_id = mysql_insert_id() )
			    {
				if ( !empty($value['accepted_date']) )
				{
				    $query = sprintf('UPDATE `contract` SET `accepted_date`=\'%s\' WHERE `id`=%d',$value['accepted_date'],$contract_id);
				    mysql_query($query);
				}
				else
				{
					$query = sprintf('UPDATE `contract` SET `accepted_date`=Now() WHERE `id`=%d',$contract_id);
				    mysql_query($query);	
				}

				if ( !empty($value['end_date']) )
				{
				    $query = sprintf('UPDATE `contract` SET `end_date`=\'%s\' WHERE `id`=%d',$value['end_date'],$contract_id);
				    mysql_query($query);
				}
			    }
			}

			if ( $err = mysql_error() ) { die($query.'<br/>'.$err); }
		    }

		    if ( is_array($contract_upd) )
		    {
			foreach ( $contract_upd as $key => $value )
			{
// Заполняем/удаляем дату подписания
			    if ( !empty($value['accepted_date']) )
			    {
					$query = sprintf('UPDATE `contract` SET `accepted_date`=\'%s\' WHERE `id`=%d',$value['accepted_date'],$key);
			    }
			    else
			    {
			    	$query = sprintf('UPDATE `contract` SET `accepted_date`=Now() WHERE `id`=%d',$key);
			    }
			    mysql_query($query);

			    if ( !empty($value['end_date']) )
			    {
					$query = sprintf('UPDATE `contract` SET `end_date`=\'%s\' WHERE `id`=%d',$value['end_date'],$key);
			    }
			    else
			    {
					$query = sprintf('UPDATE `contract` SET `end_date`=NULL WHERE `id`=%d',$key);
			    }
			    mysql_query($query);

			    if ( !empty($value['prepayment']) )
			    {
					$query = sprintf('UPDATE `contract` SET `prepayment`=\'%s\' WHERE `id`=%d',$value['prepayment'],$key);
			    }
			    else
			    {
					$query = sprintf('UPDATE `contract` SET `prepayment`=NULL WHERE `id`=%d',$key);
			    }
			    mysql_query($query);

// Меняем номер договора
			    if ( !empty($value['contract_number']) )
			    {
				$query = sprintf('UPDATE `contract` SET `contract_number`=\'%s\' WHERE `id`=%d',$value['contract_number'],$key);
			    }
			    else
			    {
				$query = sprintf('UPDATE `contract` SET `contract_number`=NULL WHERE `id`=%d',$key);
			    }
			    mysql_query($query);

// Меняем исполнителя
			    if ( is_numeric($value['executive_id']) )
			    {
				$query = sprintf('UPDATE `contract` SET `executive_id`=%d WHERE `id`=%d',$value['executive_id'],$key);
			    }
			    mysql_query($query);
			}

			if ( $err = mysql_error() ) { die($query.'<br/>'.$err); }
		    }

		    if ( is_array($arbitrary_new) )
		    {
			foreach ( $arbitrary_new as $value )
			{
			    $query = sprintf('INSERT INTO `arbitrary_field` (`customer_id`,`field_name_id`,`value`) VALUES (%d,%d,\'%s\')',$customer['id'],$value['id'],mysql_escape_string($value['value']));
			    mysql_query($query);
			}

			if ( $err = mysql_error() ) { die($err); }
		    }

		    if ( is_array($arbitrary_upd) )
		    {
			foreach ( $arbitrary_upd as $key => $value )
			{
			    $query = sprintf('UPDATE `arbitrary_field` SET `value`=\'%s\' WHERE `id`=%d AND `customer_id`=%d',mysql_escape_string($value),$key,$customer['id']);
			    mysql_query($query);
			}
			if ( $err = mysql_error() ) { die($err); }
		    }

		    mysql_query
		    (
			sprintf
			(
			    'UPDATE `customer` SET '
				.'`manager_id`=%d,'
				.'`customer_name`=\'%s\','
				.'`email`=\'%s\','
				.($_POST['email_password']!='NULL'?('`password`=\'%s\','):'`password`=%s,')
				.'`group_id`=%d,'
				.'`status_id`=%d,'
				.'`legal_region`=\'%s\','
				.'`legal_city`=\'%s\','
				.'`legal_index`=%d,'
				.'`legal_street`=\'%s\','
				.'`legal_home`=%d,'
				.'`legal_litera`=\'%s\','
				.'`legal_office`=\'%s\','
				.'`actual_region`=\'%s\','
				.'`actual_city`=\'%s\','
				.'`actual_index`=%d,'
				.'`actual_street`=\'%s\','
				.'`actual_home`=%d,'
				.'`actual_litera`=\'%s\','
				.'`actual_office`=\'%s\','
				.'`postal_region`=\'%s\','
				.'`postal_city`=\'%s\','
				.'`postal_index`=%d,'
				.'`postal_street`=\'%s\','
				.'`postal_home`=%d,'
				.'`postal_litera`=\'%s\','
				.'`postal_office`=\'%s\','
				.'`inn`=\'%s\','
				.'`okonh`=\'%s\','
				.'`okpo`=\'%s\','
				.'`kpp`=\'%s\','
				.'`bank`=\'%s\','
				.'`current_account`=\'%s\','
				.'`korr_account`=\'%s\','
				.'`bik`=\'%s\''
				.' WHERE `id`=%d',
			    mysql_escape_string($_POST['manager']),
			    mysql_escape_string($_POST['name']),
			    mysql_escape_string($_POST['email']),
			    mysql_escape_string($_POST['email_password']),
			    mysql_escape_string($_POST['group']),
			    mysql_escape_string($_POST['status']),
			    mysql_escape_string($_POST['legal_region']),
			    mysql_escape_string($_POST['legal_city']),
			    mysql_escape_string($_POST['legal_index']),
			    mysql_escape_string($_POST['legal_street']),
			    mysql_escape_string($_POST['legal_home']),
			    mysql_escape_string($_POST['legal_litera']),
			    mysql_escape_string($_POST['legal_office']),
			    mysql_escape_string($_POST['actual_region']),
			    mysql_escape_string($_POST['actual_city']),
			    mysql_escape_string($_POST['actual_index']),
			    mysql_escape_string($_POST['actual_street']),
			    mysql_escape_string($_POST['actual_home']),
			    mysql_escape_string($_POST['actual_litera']),
			    mysql_escape_string($_POST['actual_office']),
			    mysql_escape_string($_POST['postal_region']),
			    mysql_escape_string($_POST['postal_city']),
			    mysql_escape_string($_POST['postal_index']),
			    mysql_escape_string($_POST['postal_street']),
			    mysql_escape_string($_POST['postal_home']),
			    mysql_escape_string($_POST['postal_litera']),
			    mysql_escape_string($_POST['postal_office']),
			    mysql_escape_string($_POST['inn']),
			    mysql_escape_string($_POST['okonh']),
			    mysql_escape_string($_POST['okpo']),
			    mysql_escape_string($_POST['kpp']),
			    mysql_escape_string($_POST['bank_name']),
			    mysql_escape_string($_POST['account_r']),
			    mysql_escape_string($_POST['account_k']),
			    mysql_escape_string($_POST['bic']),
			    mysql_escape_string($_POST['id'])
			)
		    );

		    mysql_query('COMMIT');

		    if ( $error = mysql_error() )
		    {
			print $error;
		    }
		    else
		    {
			header('Location: '.$_SERVER['HTTP_REFERER']);
		    }
		}
	    }
	    break;

	case	'treatment.new.do':
	    if ( $_POST['account_id'] )
	    {
		if ( !empty($_POST['task']) )
		{
		    $query = sprintf
		    (
			'INSERT INTO `treatment_subscriber` (`account_id`,`date_time`,`direction`,`note`,`this_is_task`,`task_time`,`creat_manager_id`,`responsible_manager_id`,`close`)'
			    .' VALUES(%d,\'%s\',\'%s\',\'%s\',1,\'%s\',\'%d\',\'%d\',\'%d\')',
			mysql_escape_string($_POST['account_id']),
			mysql_escape_string(sprintf('%s %s:%s:00', $_POST['treatment_date'],$_POST['Time_Hour'],$_POST['Time_Minute'])),
			mysql_escape_string($_POST['direction']),
			mysql_escape_string($_POST['note']),
// Т.к. Задача, выставляем дополнительные параметры
			mysql_escape_string(sprintf('%s %02d:%02d:00',$_POST['start_date'],$_POST['start_Hour'],$_POST['start_Minute'])),
			$_SESSION['manager']['id'],
			mysql_escape_string($_POST['responsible_manager']),
			($_POST['closed']?1:0)
		    );
		}
		else
		{
		    $query = sprintf
		    (
			'INSERT INTO `treatment_subscriber` (`account_id`,`date_time`,`direction`,`note`)'
			    .' VALUES(%d,\'%s\',\'%s\',\'%s\')',
			mysql_escape_string($_POST['account_id']),
			mysql_escape_string(sprintf('%s %s:%s:00', $_POST['treatment_date'],$_POST['Time_Hour'],$_POST['Time_Minute'])),
			mysql_escape_string($_POST['direction']),
			mysql_escape_string($_POST['note'])
		    );

		}

		mysql_query($query);

		if ( mysql_affected_rows()==1 )
		{
		    header('Location: '.$_SERVER['HTTP_REFERER']);
		}
		else
		{
		    print mysql_error();
		}
	    }
	    break;

	case	'manager.set_fields.do':
	    $manager = mysql_fetch_assoc(mysql_query('SELECT * FROM `manager` WHERE `id`='.$_SESSION['manager']['id']));
	    $options = json_decode($manager['options'],true);

	    unset($options['fields']['customer_list']);

	    foreach ( $_POST as $key => $value )
	    {
		if ( $key == 'action' ) { continue; }

		if ( $_POST[$key]==1 ) { $options['fields']['customer_list'][$key] = 1; }
	    }

	    mysql_query(sprintf('UPDATE `manager` SET `options`=\'%s\' WHERE `id`=%d',json_encode($options),$_SESSION['manager']['id']))||die('An error occured while update');
	    $_SESSION['manager']['options'] = $options;

	    header('Location: '.$_SERVER['HTTP_REFERER']);
	    exit();

	    break;

	case	'service.new.do':
	    if ( is_numeric($_POST['account_id']) && is_numeric($_POST['service_name']) && is_numeric($_POST['executive']) )
	    {
	    	//если это услуги voice id = 3 то делаем через тразакцию
	    	if ($_POST['service_name']==3)
	    	{
				if ( is_numeric($_POST['phone_rate_id']) && !empty($_POST['phone_number']) )
				{
			    	mysql_query('START TRANSACTION');
				}
			}

			//если это услуга не voip id=30 то добавляем услугу
			if ($_POST['service_name']!=30)
			{
				mysql_query
				(
				    sprintf
				    (
					'INSERT INTO `service` (`account_id`,`service_name_id`,`executive_id`,`quantity`,`cost`,`monthly`,`start_date`,`stop_date`,`date_of_invoice`,`payment_delay`,`contract_id`)'
					    .' VALUES (%d,%d,%d,\'%0.2f\',%d,%d,\'%s\',\'%s\',%d,%d,%d)',
					$_POST['account_id'],
					$_POST['service_name'],
					$_POST['executive'],
					$_POST['quantity'],
					$_POST['cost'],
					($_POST['monthly']?1:0),
					mysql_escape_string($_POST['start_date']),
					mysql_escape_string($_POST['stop_date']),
					$_POST['date_of_invoice'],
					$_POST['payment_delay'],
					$_POST['contract_id']
				    )
				);
			}
			else
			{
				$query='call add_voip3(%d,\'%d\',\'%d\',\'%s\',%s,%s,%s,%s,%s,%s,%d,%d,';

				$_POST['device_own']="'".$_POST['device_own']."'";
				if (strlen($_POST['SN']) == 0) 
				{
					$_POST['SN']="NULL";
					$query=$query.'%s';
				} 
				else
				{
					$query=$query.'\'%s\'';
				}

				if (strlen($_POST['device_model']) == 0) 
				{
					$_POST['device_model']="NULL";
					$query=$query.',%s';
				}
				else
				{
					$query=$query.',\'%s\'';
				}

				if (strlen($_POST['device_login']) == 0) 
				{
					$_POST['device_login']="NULL";
					$query=$query.',%s';
				} 
				else
				{
					$query=$query.',\'%s\'';
				}
				

				if (strlen($_POST['device_password']) == 0) 
				{
					$_POST['device_password']="NULL";
					$query=$query.',%s';
				}
				else
				{
					$query=$query.',\'%s\'';	
				}

				//echo("phone_number_voip_multiline - ");
				//echo($_POST['phone_number_voip_multiline']);
				//echo("\n");

				if (strlen($_POST['phone_number_voip_multiline']) == 0) 
				{
					$_POST['phone_number_voip_multiline']="NULL";
				}

				//echo("phone_number_voip_multiline - ");
				//echo($_POST['phone_number_voip_multiline']);
				//echo("\n");


				$query=$query.',%d,\'%s\',\'%s\',%d,%d,%d,%d,%d)';

				//$quer=sprintf
				//    (
				//    $query,
				//	$_POST['account_id'],
				//	$_POST['phone_number_voip'],
				//	$_POST['phone_number_voip_multiline'],
				//	$_POST['voip_service_password'],
				//	$_POST['city_uplink_id'],
				//	$_POST['zona_mobile_uplink_id'],
				//	$_POST['zona_stationary_uplink_id'],
				//	$_POST['long_distance_uplink_id'],
				//	$_POST['international_uplink_id'],
				//	$_POST['device_own'],
				//	$_POST['phone_port'],
				//	$_POST['number_of_channel'],
				//	$_POST['SN'],
				//	$_POST['device_model'],
				//	$_POST['device_login'],
				//	$_POST['device_password'],
				//	$_POST['cost'],
				//	mysql_escape_string($_POST['start_date']),
				//	mysql_escape_string($_POST['stop_date']),
				//	$_POST['date_of_invoice'],
				//	$_POST['payment_delay'],
				//	$_POST['executive'],
				//	$_POST['phone_rate_id']
				//  );

				//echo($quer);

				mysql_query
				(
				    sprintf
				    (
				    $query,
					$_POST['account_id'],
					$_POST['phone_number_voip'],
					$_POST['phone_number_voip_multiline'],
					$_POST['voip_service_password'],
					$_POST['city_uplink_id'],
					$_POST['zona_mobile_uplink_id'],
					$_POST['zona_stationary_uplink_id'],
					$_POST['long_distance_uplink_id'],
					$_POST['international_uplink_id'],
					$_POST['device_own'],
					$_POST['phone_port'],
					$_POST['number_of_channel'],
					$_POST['SN'],
					$_POST['device_model'],
					$_POST['device_login'],
					$_POST['device_password'],
					$_POST['cost'],
					mysql_escape_string($_POST['start_date']),
					mysql_escape_string($_POST['stop_date']),
					$_POST['date_of_invoice'],
					$_POST['payment_delay'],
					$_POST['executive'],
					$_POST['phone_rate_id'],
					$_POST['contract_id']
				    )
				);
			}


			//если это услуга voice то добавляем новый номер в таблицу номеров и закрываем транзакцию если успешно
			if ($_POST['service_name']==3)
			{
				if ( is_numeric($_POST['phone_rate_id']) && !empty($_POST['phone_number']) )
				{
				    if ( $service_id = mysql_insert_id() )
				    {
						mysql_query
						(
						    sprintf
						    (
							'INSERT INTO `service_phone_number` (`service_id`,`phone_rate_id`,`phone_number`)'
							    .' VALUES(%d,%d,\'%s\')',
							$service_id,
							$_POST['phone_rate_id'],
							$_POST['phone_number']
						    )
						);
						mysql_query('COMMIT');

						header('Location: '.$_SERVER['HTTP_REFERER'].'#services');
						exit();
				    }
				}
			}

			if ( mysql_affected_rows()==1 )
			{
			    header('Location: '.$_SERVER['HTTP_REFERER'].'#services');
			    exit();
			}
			else if ( $err = mysql_error() )
			{
			    die($err);
			}
			else
			{
			    die('Unknown error');
			}
		}
		break;

	case	'contact.new.do':
	    if ( $_POST['account_id'] )
	    {
		mysql_query
		(
		    sprintf
		    (
			'INSERT INTO `contact` (`account_id`,`contact_name`,`post`,`phone_number`,`email`,`note`)'
			    .' VALUES(%d,\'%s\',\'%s\',\'%s\',\'%s\',\'%s\')',
			mysql_escape_string($_POST['account_id']),
			mysql_escape_string($_POST['contact_name']),
			mysql_escape_string($_POST['post']),
			mysql_escape_string($_POST['phone_number']),
			mysql_escape_string($_POST['email']),
			mysql_escape_string($_POST['note'])
		    )
		);
		if ( mysql_affected_rows()==1 )
		{
		    header('Location: '.$_SERVER['HTTP_REFERER'].'#contact');
		}
		else
		{
		    print mysql_error();
		}
	    }
	    break;

	default:
	    print "module not found<br/>";
	    break;
    }

    print_r($_POST);
}
?>